"""
服务器通信模块
Server communication module for sending data
"""

import requests
import time
import logging
from config import SERVER_CONFIG

logger = logging.getLogger(__name__)

class ServerClient:
    def __init__(self):
        self.server_url = SERVER_CONFIG['url']
        self.timeout = SERVER_CONFIG['timeout']
        self.retry_attempts = SERVER_CONFIG['retry_attempts']
        self.retry_delay = SERVER_CONFIG['retry_delay']
    
    def send_data_to_server(self, data):
        """发送数据到远程服务器"""
        for attempt in range(self.retry_attempts):
            try:
                response = requests.post(
                    self.server_url, 
                    json=data, 
                    timeout=self.timeout
                )
                if response.status_code == 200:
                    logger.info(f"数据成功发送到服务器: {data}")
                    return True
                else:
                    logger.warning(f"服务器响应错误: {response.status_code}")
            except requests.exceptions.RequestException as e:
                logger.error(f"发送数据到服务器失败 (尝试 {attempt + 1}/{self.retry_attempts}): {e}")
                if attempt < self.retry_attempts - 1:
                    time.sleep(self.retry_delay)
        
        return False
    
    def should_send_data(self, data):
        """检查是否应该发送数据到服务器"""
        location_source = data.get('location', {}).get('location_source', '')
        return location_source != 'GPS_no_signal'
